﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using System.IO;
using System.Linq;

using AKMII.DMRA.Common;
using AKMII.DMRA.Business.Management;
using AKMII.DMRA.Business.Service;
using AKMII.DMRA.Business.Rule;

namespace AKMII.DMRA.Web
{
    public partial class ShoppingCart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.hiddenIsOrder.Value = "0";
                OrderManager om = new OrderManager();
                Order order = om.GetOrder(User.Identity.Name, CurrentPeriod.Month, CurrentPeriod.Year);
                if (order == null)
                {
                    order = new Order();
                    order.PeroidMonth = CurrentPeriod.Month;
                    order.PeroidYear = CurrentPeriod.Year;
                    order.AccountId = User.Identity.Name;
                }
                else
                {
                    if (order.IsPurchased)
                    {
                        this.hiddenIsOrder.Value = "1";
                    }
                }

                Session["CartZips"] = order.Zips.OrderBy(c => c.Agent).ThenBy(c => string.IsNullOrEmpty(c.Week) ? 0 : int.Parse(c.Week)).ToList<LeadBlock>();
                BindDataList();
                BindLabelInfo(order);
            }
        }

        private void BindDataList()
        {
            List<LeadBlock> zips = new List<LeadBlock>();
            zips = (List<LeadBlock>)Session["CartZips"];
            GridView1.DataSource = zips;
            GridView1.DataBind();
            int total = 0;
            int sum = 0;
            int currentSelected = 0;
            int currentUnselected = 0;
            int activeleads = 0;
            int lapseleads = 0;
            int bussinessleads = 0;
            int neighborleads = 0;
            int cactiveleads = 0;
            int clapseleads = 0;
            int cbussinessleads = 0;
            int cneighborleads = 0;
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chbItem");
                cb.Attributes.Add("onclick", "ChangeInfo();");
                Label lAgent = (Label)GridView1.Rows[i].Cells[0].FindControl("lblAgent");
                Label lWeek = (Label)GridView1.Rows[i].Cells[0].FindControl("lblWeek");
                if (lAgent.Text.Length > 1)
                {
                    lWeek.Text = lAgent.Text.Split(' ')[0];
                    lAgent.Text = lAgent.Text.Substring(lAgent.Text.IndexOf(' ') + 1);
                }
                //int rowleads = Convert.ToInt32(GridView1.Rows[i].Cells[8].Text);
                cb.Checked = zips[GridView1.PageSize * GridView1.PageIndex + i].IsOrderInOneALN;

                if (cb.Checked)
                {
                    if (zips[GridView1.PageSize * GridView1.PageIndex + i].Type == OrderType.All || zips[GridView1.PageSize * GridView1.PageIndex + i].Type == OrderType.ALN)
                    {
                        currentSelected = currentSelected + Convert.ToInt32(GridView1.Rows[i].Cells[10].Text) + Convert.ToInt32(GridView1.Rows[i].Cells[11].Text);
                        cactiveleads = cactiveleads + Convert.ToInt32(GridView1.Rows[i].Cells[10].Text);
                        clapseleads = clapseleads + Convert.ToInt32(GridView1.Rows[i].Cells[11].Text);
                        cneighborleads = cneighborleads + Convert.ToInt32(GridView1.Rows[i].Cells[12].Text);
                    }
                    if (zips[GridView1.PageSize * GridView1.PageIndex + i].Type == OrderType.All || zips[GridView1.PageSize * GridView1.PageIndex + i].Type == OrderType.Business)
                    {
                        cbussinessleads = cbussinessleads + Convert.ToInt32(GridView1.Rows[i].Cells[13].Text);
                    }
                }
                else
                {
                    currentUnselected = currentUnselected + Convert.ToInt32(GridView1.Rows[i].Cells[10].Text) + Convert.ToInt32(GridView1.Rows[i].Cells[11].Text);
                }
            }
            if (Session["CartZips"] != null)
            {
                for (int i = 0; i < zips.Count; i++)
                {
                    if (zips[i].Type == OrderType.ALN || zips[i].Type == OrderType.All)
                    {
                        sum = sum + zips[i].ActiveLeadCount + zips[i].LapsedLeadCount;
                        activeleads = activeleads + zips[i].ActiveLeadCount;
                        lapseleads = lapseleads + zips[i].LapsedLeadCount;
                        neighborleads = neighborleads + zips[i].NeighborLeadCount;
                        total = total + zips[i].ActiveLeadCount + zips[i].LapsedLeadCount;
                    }
                    if (zips[i].Type == OrderType.Business || zips[i].Type == OrderType.All)
                    {
                        bussinessleads = bussinessleads + zips[i].BusinessLeadCount;
                    }
                }
            }
            this.hiddenNum.Value = (sum - currentSelected).ToString();
            this.hiddenUnselectedNum.Value = (total - sum - currentUnselected).ToString();
            this.hiddenActive.Value = (activeleads - cactiveleads).ToString();
            this.hiddenBussiness.Value = (bussinessleads - cbussinessleads).ToString();
            this.hiddenLapse.Value = (lapseleads - clapseleads).ToString();
            this.hiddenNeighbor.Value = (neighborleads - cneighborleads).ToString();
            this.lbActiveLead.Text = activeleads.ToString();
            this.lbBussinessLead.Text = bussinessleads.ToString();
            this.lbLapseLead.Text = lapseleads.ToString();
            this.lbNeighborLead.Text = neighborleads.ToString();
            this.lbAllLeads.Value = sum.ToString();
            this.hiddenEstimate.Value = GetActiveLeadCount();
            this.lbCartAgent.Text = sum.ToString();
        }

        private void BindLabelInfo(Order order)
        {
            int cartcount = 0;
            for (int i = 0; i < order.Zips.Count; i++)
            {
                if (order.Zips[i].Type == OrderType.ALN || order.Zips[i].Type == OrderType.All)
                {
                    cartcount = cartcount + order.Zips[i].ActiveLeadCount + order.Zips[i].LapsedLeadCount;
                }
            }
            this.lbCartAgent.Text = cartcount.ToString();
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            if (!CurrentPeriod.IsOrderPeriod)
            {
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),
                    "isOrderPeriod", "<script type='text/javascript'>alert('Sorry,you can not order now for the cut off date reached! ');</script>");
                BindDataList();
                return;
            }

            List<LeadBlock> zips = new List<LeadBlock>();
            zips = (List<LeadBlock>)Session["CartZips"];

            OrderManager om = new OrderManager();
            Order order = om.GetOrder(User.Identity.Name, CurrentPeriod.Month, CurrentPeriod.Year);
            if (order == null)
            {
                order = new Order();
                order.PeroidMonth = CurrentPeriod.Month;
                order.PeroidYear = CurrentPeriod.Year;
                order.AccountId = User.Identity.Name;
            }
            else
            {
                if (order.IsPurchased)
                {
                    Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),
                        "isPurchased", "<script type='text/javascript'>alert('You have already purchased order for this month! ');</script>");
                    BindDataList();
                    return;
                }
            }
            if (order.Zips == null)
            {
                order.Zips = new List<LeadBlock>();
            }
            else
            {
                order.Zips.Clear();
            }
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chbItem");
                zips[GridView1.PageSize * GridView1.PageIndex + i].IsOrderInOneALN = cb.Checked;
            }

            for (int i = 0; i < zips.Count; i++)
            {
                if (zips[i].IsOrderInOneALN)
                {
                    order.Zips.Add(zips[i]);
                }
            }
            if (om.ManageOrder(order))
            {
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "Ordered", "<script type='text/javascript'>alert('Congratulations!You have refreshed successfully.');</script>");
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "failed", "<script type='text/javascript'>alert('you have failed! ');</script>");
            }
            Session["CartZips"] = order.Zips;
            BindDataList();
            BindLabelInfo(order);
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            List<LeadBlock> zips = (List<LeadBlock>)Session["CartZips"];
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chbItem");
                zips[GridView1.PageSize * GridView1.PageIndex + i].IsOrderInOneALN = cb.Checked;
            }

            Session["CartZips"] = zips;
            GridView1.PageIndex = e.NewPageIndex;
            BindDataList();
        }

        protected void btnOrder_Click(object sender, EventArgs e)
        {
            if (!CurrentPeriod.IsOrderPeriod)
            {
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),
                    "isOrderPeriod", "<script type='text/javascript'>alert('Sorry,you can not order now for the cut off date reached.! ');</script>");
                BindDataList();
                return;
            }

            List<LeadBlock> zips = new List<LeadBlock>();
            zips = (List<LeadBlock>)Session["CartZips"];
            OrderManager om = new OrderManager();
            Order order = om.GetOrder(User.Identity.Name, CurrentPeriod.Month, CurrentPeriod.Year);
            if (order == null)
            {
                order = new Order();
                order.PeroidMonth = CurrentPeriod.Month;
                order.PeroidYear = CurrentPeriod.Year;
                order.AccountId = User.Identity.Name;
            }
            else
            {
                if (order.IsPurchased)
                {
                    Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),
                        "isPurchased", "<script type='text/javascript'>alert('Sorry,you have already purchased orders for this month or the cut off date ended! ');</script>");
                    BindDataList();
                    return;
                }
            }
            //if (!order.IsAssigned)
            //{
            //    Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),
            //          "isAssigned", "<script type='text/javascript'>alert('Sorry, you are not be allowed to place order until all ordered lead blocks assigned! ');</script>");
            //    return;
            //}
            if (order.Zips == null)
            {
                order.Zips = new List<LeadBlock>();
            }
            else
            {
                order.Zips.Clear();
            }
            if (om.PurchaseOrder(order.Id))
            {
                this.hiddenIsOrder.Value = "1";
                Thread thread = new Thread(new ThreadStart(SendReport));
                thread.Start();
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),
                    "ordersuccess",
                    "<script type='text/javascript'>alert('Congratulations! Your order for " + this.lbAllLeads.Value + " active & lapse leads and " + this.lbBussinessLead.Text + " business leads has been sent for the month of " + Utility.GetMonthName(CurrentPeriod.Month) + " ');</script>");
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "isPurchased", "<script type='text/javascript'>alert('Sorry,order failed, you can try again or contact admin! ');</script>");
            }
            BindLabelInfo(order);
        }

        protected void SendReport()
        {
            using (CommonServiceClient client = new CommonServiceClient())
            {
                client.SendReport(User.Identity.Name, CurrentPeriod.Month, CurrentPeriod.Year);
            }
        }

        public string GetActiveLeadCount()
        {
            string leadCount = string.Empty;

            User user = Session["CurrentUser"] as User;

            if (user != null)
            {
                leadCount = (user.AgentNumber * SystemConfiguration.CommonSetting.LeadPerAgent * 4).ToString();
            }
            else
            {
                FormsAuthentication.SignOut();
                Response.Redirect(Constants.LoginUrl);
            }

            return leadCount;
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LeadBlock lb = e.Row.DataItem as LeadBlock;
                e.Row.ToolTip = string.Format("Active Stop Count:{0}\nLasped Stop Count:{1}\nNeighbor Stop Count:{2}\nBusiness Stop Count:{3}",
                    lb.ActiveLeadCount, lb.LapsedLeadCount, lb.NeighborLeadCount, lb.BusinessLeadCount);
            }
        }
    }
}
